<?php
/* ----------------- Copyright Notice ----------------------
This library are copyright of Digdaya Technologies. Please
use it as is condition approved. You may not use it or
redistribute, sell it, included in software package and in
any condition without mentioned this copyright notice.

If you want to obtain copyright of this library, or if you had
any question regarding this copyright please free to contact
Digdaya Teknologi at copyright@digdaya.com or job@arifwidi.com.

Copyright �2002-2003 Digdaya Teknologi. All rights reserved.
----------------------- End Copyright --------------------- */

/* VARIABLE DECLARATION */

$LIB_NO_ERROR = true;
$LIB_ERR_MSG = "";
$LIB_NO_MSG = true;
$LIB_MSG = "";

/* FUNCTIONS */

$LIB_LANGUAGE = "id";

/**
* Set default language for any localization string by ifi
*
* @return void
* @param string $langstr
*/
function setLanguage($langstr)
{
	global $LIB_LANGUAGE;
	$LIB_LANGUAGE = $langstr;
	$_SESSION['lang'] = $LIB_LANGUAGE;
}

/**
* Get language by ifi
*
* @return language_id
*/
function getLanguage()
{
	global $LIB_LANGUAGE;
	if ( $_SESSION['lang'] != '' ) {
		$LIB_LANGUAGE = $_SESSION['lang'];
	}
	return $LIB_LANGUAGE;
}

function isErr()
{
	global $LIB_NO_ERROR;
	return !$LIB_NO_ERROR;
}

function showError() {
    global $LIB_ERR_MSG;
    global $LIB_NO_ERROR;
    global $LIB_MSG;
    global $LIB_NO_MSG;
    if(!$LIB_NO_ERROR) {
        $errMsg = '<ul class="error">'.$LIB_ERR_MSG.'</ul>';
        return $errMsg;
    }
    if(!$LIB_NO_MSG) {
        $Msg = '<ul class="message">'.$LIB_MSG.'</ul>';
        return $Msg;
    }
}

function checkError($var, $msgErr) {
	if ($var=='') addError($msgErr);
}

function addError($msgError) {
    global $LIB_ERR_MSG;
    global $LIB_NO_ERROR;
    if ($msgError!='') {
        $LIB_ERR_MSG .= '<li>'.$msgError.'</li>';
        $LIB_NO_ERROR = false;
    }
}

function addMsg($msgText) {
    global $LIB_MSG;
    global $LIB_NO_MSG;
    if ($msgText!='') {
        $LIB_MSG .= '<li>'.$msgText.'</li>';
        $LIB_NO_MSG = false;
    }
}

function giveAttr($varcek, $varval, $strgive) {
    if($varcek==$varval) {
        return $strgive;
    }
}

function giveCheck($varcek, $varval) {
    return in_array($varcek, $varval)? ' selected':'';
}

/* -----------------------------------------
            Date & time Function
------------------------------------------ */
function subTime($timestamp, $seconds,$minutes,$hours,$days,$months,$years) {
    $mytime = mktime(1+$hours,0+$minutes,0+$seconds,1+$months,1+$days,1970+$years);
    return $timestamp - $mytime;
}

function addTime($timestamp, $seconds,$minutes,$hours,$days,$months,$years) {
    $mytime = mktime(1+$hours,0+$minutes,0+$seconds,1+$months,1+$days,1970+$years);
    return $timestamp + $mytime;
}

function dayOfWeek($timestamp) {
    return intval(strftime("%w",$timestamp));
}

function daysInMonth($timestamp) {
    $timepieces = getdate($timestamp);
    $thisYear = $timepieces["year"];
    $thisMonth = $timepieces["mon"];
    for($thisDay=1;checkdate($thisMonth,$thisDay,$thisYear);$thisDay++);
    return $thisDay;
}

function firstDayOfMonth($timestamp) {
    $timepieces = getdate($timestamp);
    return mktime( $timepieces["hours"],
    $timepieces["minutes"],
    $timepieces["seconds"],
    $timepieces["mon"],
    1,
    $timepieces["year"]);
}

function monthStartWeekDay($timestamp) {
    return dayOfWeek(firstDayOfMonth($timestamp));
}

function weekDayString($weekday) {
    global $hariArray;
    return $hariArray[$weekday];
}

function monthString($monthnum) {
    global $bulanArray;
    return $bulanArray[$monthnum];
}

function stripTime($timestamp) {
    $timepieces = getdate($timestamp);
    return mktime($timepieces["hours"],
    $timepieces["minutes"],
    $timepieces["seconds"],
    $timepieces["mon"],
    $timepieces["mday"],
    $timepieces["year"]);
}

function getDayOfYear($timestamp) {
    $timepieces = getdate($timestamp);
    return intval($timepieces["yday"]);
}

function getYear($timestamp) {
    $timepieces = getdate($timestamp);
    return intval($timepieces["year"]);
}

function dayDiff($timestamp1,$timestamp2) {
    $dayInYear1 = getDayOfYear($timestamp1);
    $dayInYear2 = getDayOfYear($timestamp2);
    return ((getYear($dayInYear1)*365 + $dayInYear1) - (getYear($dayInYear2)*365 + $dayInYear2));
}

function getDayDate($waktu = NULL, $shape = 0) {
	if (is_null($waktu)) $waktu=getdate(time());
	//$jam = date('H:i', $waktu);
	$jam = $waktu["hours"].':'.$waktu["minutes"];
	switch ($shape) {
        case 0: $mystr = $waktu["mday"] . '/' . $waktu["mon"] . '/' . $waktu["year"];break;
        case 1: $mystr = weekDayString($waktu["wday"]) . ', ' . $waktu["mday"] . ' ' . monthString($waktu["mon"]) . ' ' . $waktu["year"];break;
        case 2: $mystr = $waktu["mday"] . '/' . $waktu["mon"] . '/' . $waktu["year"] . ' ' . $jam;break;
        case 3: $mystr = weekDayString($waktu["wday"]) . ', ' . $waktu["mday"] . ' ' . monthString($waktu["mon"]) . ' ' . $waktu["year"] . ' ' . $jam;break;
        default: $mystr = $waktu["mday"] . '/' . $waktu["mon"] . '/' . $waktu["year"];break;
    }
    return $mystr;
}

/* -------------------------------------------------------
             Run and execution modules
------------------------------------------------------- */

function validateEmail($email) {
    return ereg("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@([0-9a-z](-?[0-9a-z])*\.)+[a-z]{2}([zmuvtg]|fo|me)?$",$email);
}

function validateDate($date) {
    return ereg("^([0-9]{1,2})/([0-9]{1,2})/([0-9]{4})$", $date);
}

function validatePassword($pass, $strength = false) {
    if (!$strength)
        return ereg("^([A-Za-z0-9]{6,20})$", $pass);
    else
        //Use strength check with character length and car pattern recognition
        return ereg("^([A-Za-z0-9]{6,20})$", $pass);
}

function validateName($name) {
    return ereg("^([A-Za-z�-��-��-� \.,]{2,})$", $name);
}

function getDateTime($tanggal) {
	if (ereg("^([0-9]{1,2})/([0-9]{1,2})/([0-9]{4}) ([0-9]{1,2}):([0-9]{1,2})$", $tanggal)) {
		list($tgl, $wkt) = explode(" ",$tanggal);
		list($day, $bln, $thn) = explode("/",$tgl);
		list($hr, $mn) = explode(":",$wkt);
		return $thn.'-'.$bln.'-'.$day.' '.$hr.':'.$mn.':10';
	} else {
		if (ereg("^([0-9]{1,2})/([0-9]{1,2})/([0-9]{4})$", $tanggal)) {
			list($day, $bln, $thn) = explode("/",$tanggal);
			return $thn.'-'.$bln.'-'.$day.' 00:00:00';
		} else {
			return NULL;
		}
	}
}

function getTanggalWaktu($date, $fmt = 1) {
	if (($date!='')&&(!is_null($date))) {
		list($tgl, $wkt) = explode(" ",$date);
		list($thn, $bln, $tgl) = explode("-",$tgl);
		list($hr, $mn, $sc) = explode(":",$wkt);

		if ($fmt==1) {
			if ($hr == '') {
				return $tgl.'/'.$bln.'/'.$thn;
			} else {
				return $tgl.'/'.$bln.'/'.$thn.' '.$hr.':'.$mn;
			}
		} else {
			if ($hr == '') {
				return $tgl.'/'.$bln.'/'.substr($thn,-2);
			} else {
				return $tgl.'/'.$bln.'/'.substr($thn,-2).' '.$hr.':'.$mn;
			}
		}
	} else {
		return NULL;
	}
}

function getTimestamp($tanggal, $mode='-') {
	list($hr, $mn, $sc) = explode(":",$tanggal);
	switch ($mode) {
    case '/': list($tgl, $bln, $thn) = explode("/",$tanggal);break;
	case '-': list($thn, $bln, $tgl) = explode("-",$tanggal);break;
	default: list($tgl, $bln, $thn) = explode("/",$tanggal);break;
	}

    return mktime($hr, $mn, $sc, $bln, $tgl, $thn);
}

function stripBreak($text) {
	$pattern = Array(
		"/\r\n   /",
		"/\r\n/",
		"/\[X\]\[X\]/",
		"/\[X\]/",
		"/\r\n/",
	);

	$replacement = Array(
		"[X][X]",
		"[X]",
		"\r\n",
		" ",
		"\r\n\r\n",
	);

	return preg_replace($pattern, $replacement, $text);
}

function parseAttrGambar($matches)
{
	global $HTTP_PICTURE;
	$arr_gambar = array();
	$arr_style = array();
	$str_gambar = "";

	// Initialize parameter
	$prm_kotak = false;
	$prm_align = null;
	$prm_teks = null;
	$prm_href = null;

	// Get file and parameters
	$datagambar = explode("|", $matches[1]);
	$arr_gambar[] = 'src="' . $HTTP_PICTURE . $datagambar[0] . '"';

	if ( count($datagambar)>1 )
	{
		for ( $i=1; $i < count($datagambar); $i++)
		{
			$data = $datagambar[$i];

			// '/(http:\/\/(.*)\/)[\S]*/'
			if ( ( $data == "kanan" ) || ( $data == "kiri" ) )
			{
				$prm_align = ( $data == "kiri" ) ? "left" : "right";
			}
			elseif ( $data == "kotak" )
			{
				$prm_kotak = true;
			}
			elseif ( preg_match('/(http:\/\/)(\w+)/', $data) )
			{
				$prm_href = $data;
			}
			elseif ( preg_match('/(teks=)(\w+)/', $data ) )
			{
				$prm_teks = explode("=", $data);
				$prm_teks = $prm_teks[1];
				$arr_gambar[] = 'alt="' . htmlentities($prm_teks, ENT_QUOTES) . '"';
				$arr_gambar[] = 'title="' . htmlentities($prm_teks, ENT_QUOTES) . '"';
			}
		}
	}

	$altada = false;
	for ( $i=0; $i < count($arr_gambar); $i++ )
	{
		if ( preg_match('/alt=/i', $arr_gambar[$i]) )
		{
			$altada = true;
		}
	}

	if ( !$altada )
		$arr_gambar[] = 'alt=""';

	if ( $prm_kotak )
			$arr_gambar[] = 'class="gbr-kotak"';

	$str_gambar = '<img ' . implode(" ", $arr_gambar) . ' border="0"/>';

	if ( $prm_href != null )
		$str_gambar = '<a href="' . $prm_href . '">' . $str_gambar . '</a>';

	if ( count($arr_style) > 0 )
		$str_style = ' style="' . implode("",$arr_style) . '"';

	if ( $prm_teks != null )
		$str_gambar = '<span class="descgambar">' . $str_gambar . '<br/>' . $prm_teks . '</span>';

	if ( $prm_align != null )
		$str_gambar = '<span class="gbr-' . $prm_align . '">' . $str_gambar . '</span>';

	return $str_gambar;
}

function parseGambar($str)
{
	return preg_replace_callback("/\[Gambar:(.*)\]/i", "parseAttrGambar", $str);
}

function parseAttrFile($matches)
{
	global $HTTP_PICTURE;
	$arr = array();

	$data = explode("|", $matches[1]);

	// bentuk nama file
	$arr[] = 'href="' . $HTTP_PICTURE . $data[0] . '"';
	$filenya = $data[0];

	$classnya = "download";
	$extnya = explode(".", $filenya);
	$extnya = $extnya[1];
	switch ( strtolower($extnya) )
	{
		case "mp3" : $classnya .= "music";break;
		case "wav" : $classnya .= "music";break;
		case "wmv" : $classnya .= "video";break;
		case "avi" : $classnya .= "video";break;
		case "pdf" : $classnya .= "pdf";break;
		case "doc" : $classnya .= "word";break;
		case "rtf" : $classnya .= "word";break;
		case "txt" : $classnya .= "docs";break;
		case "mdb" : $classnya .= "office";break;
		case "xls" : $classnya .= "xls";break;
		case "ppt" : $classnya .= "office";break;
		case "rar" : $classnya .= "zip";break;
		case "zip" : $classnya .= "zip";break;
		case "gz" : $classnya .= "zip";break;
		case "tar" : $classnya .= "zip";break;
		case "exe" : $classnya .= "appz";break;
	}

	if ( count($data)>1 )
	{
		for ( $i=1; $i < count($data); $i++)
		{
			if ( preg_match('/\"{1}(.*)\"{1}/', $data[$i]) )
			{
				$strnya = str_replace("\"", "", $data[$i]);
				$arr[] = 'title="' . $strnya . '"';
			}
		}
	}

	if ( $strnya == '' ) $strnya = $filenya;
	$data = implode(" ", $arr);
	$data = '<a ' . $data . ' class="' . $classnya . '">' . $strnya . '</a>';
	return $data;
}

function parseFile($str)
{
	return preg_replace_callback("/\[File:(.*)\]/i", 'parseAttrFile', $str);
}

function parsesContent($text, $break = 1) {
	if (($break=='1')||($break==1)) {
		$text = Markdown($text);
		$text = parseFile($text);
		$text = parseGambar($text);

		echo $text;
	} else {
		echo $text;
	}
}